<template>
  <div>
    <div v-if="value" class="image">
      <el-image
        :src="website + value"
        :preview-src-list="[website + value]"
        fit="fill"
      >
      </el-image>
      <div class="mask">
        <span title="移除" @click.stop="removeImage">
          <i class="el-icon-circle-close" />
        </span>
      </div>
    </div>
    <el-upload
      v-else
      ref="upload"
      class="upload-demo"
      :headers="headers"
      drag
      :data="{ type: 1 }"
      :action="uploadUrl"
      :limit="1"
      :multiple="false"
      :show-file-list="false"
      :on-error="handleUploadError"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
      <div v-if="tip" slot="tip">{{ tip }}</div>
    </el-upload>
  </div>
</template>

<script>
import {target, website} from "@/utils/config";

export default {
  data() {
    return {
      loading: null,
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: window.localStorage.getItem(`token-${target}`),
      },
      website,
    };
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    tip: {
      type: String,
      default: "",
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["jpg", "jpeg", "gif", "bmp", "png"],
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
  },
  methods: {
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传1张图片`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
      this.$refs.upload.clearFiles()
      this.loading.close();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.loading.close();
      if (+res.code === 200) {
        this.$message.success("上传成功");
        this.$emit("input", res.data[0]);
      } else {
        this.$refs.upload.clearFiles();
        this.$message.error(res.msg);
      }
    },
    removeImage() {
      this.$emit("input", "");
    },
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.toLowerCase().indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.warning(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.warning(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.loading = this.$loading({
        lock: true,
        text: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return true;
    },
  },
  watch: {},
};
</script>

<style scoped lang="scss">
.image {
  position: relative;
  .mask {
    position: absolute;
    top: -10px;
    right: -10px;
    .el-icon-circle-close
    {
      font-size: 25px;
    }
    .el-icon-circle-close:hover {
      cursor: pointer;
      font-size: 30px;
    }
  }
}
</style>
